package com.fjwt.gz.service.activity.platform.acte027;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.fjwt.gz.core.cache.RedisUtil;
import com.fjwt.gz.core.constants.Constants;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.db.bo.ActivityAwardAndSettingBo;
import com.fjwt.gz.db.bo.ActivityAwardBO;
import com.fjwt.gz.db.bo.ActivityUserTimesBO;
import com.fjwt.gz.db.dto.FansActivityDTO;
import com.fjwt.gz.db.entity.*;
import com.fjwt.gz.db.vo.ActivityAwardVO;
import com.fjwt.gz.service.activity.BaseActivityDTO;
import com.fjwt.gz.service.activity.BaseActivityService;
import com.fjwt.gz.service.impl.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class ACTE027Service extends BaseActivityService<Object> {

    private static final String logPrefix = "【老客唤醒活动】";

    @Autowired
    private OldFansInfoService oldFansInfoService;

    @Autowired
    private ScoreRecordTotalService scoreRecordTotalService;

    @Autowired
    private FansUserService fansUserService;

    @Autowired
    private ActivityAwardService activityAwardService;

    @Autowired
    private AwardScoreService awardScoreService;

    @Autowired
    private ActivitySettingService activitySettingService;

    @Autowired
    private AwardSettingService awardSettingService;

    @Autowired
    private SendAwardService sendAwardService;
    @Autowired
    private FansAuthService fansAuthService;
    @Autowired
    private FansSourceService fansSourceService;
    @Autowired
    private AgentInfoService agentInfoService;

    /**
     * 新建活动
     */
    @Override
    public void add(BaseActivityDTO activityDTO) {
        log.info("新增ACTE027的活动");
        super.add(activityDTO);
    }

    /**
     * 修改活动
     */
    @Override
    public void update(BaseActivityDTO activityDTO) {
        log.info("更新ACTE027的活动");
        super.update(activityDTO);
    }

    /**
     * 删除活动
     */
    @Override
    public void delete(Long activityId) {
        log.info("删除ACTE027的活动");
        super.delete(activityId);
    }

    /**
     * 活动详情--pc
     */
    @Override
    public BaseActivityDTO detail(Long activityId) {
        log.info("查看ACTE027的活动详情");
        BaseActivityDTO baseActivityDetailsVO = super.detail(activityId);
        return baseActivityDetailsVO;
    }

    /**
     * 参与活动
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ActivityAwardVO takePartIn(FansActivityDTO fansActivityDTO) {
        log.info("进入{}", logPrefix);
        super.takePartIn(fansActivityDTO);
        Long fansId = fansActivityDTO.getFansId();
        Long activityId = fansActivityDTO.getActivityId();
        String appId = fansActivityDTO.getAppId();

        ActivityAwardVO activityAwardVO = new ActivityAwardVO();
        activityAwardVO.setOldClient(false);
        activityAwardVO.setIsMove(0);
        activityAwardVO.setActivityId(activityId);

        // 查询用户实名信息
        FansAuthEntity fansAuthEntity = fansAuthService.getOne(FansAuthEntity.gw()
                .eq(FansAuthEntity::getAgentNo, fansActivityDTO.getLocationAgentNo())
                .eq(FansAuthEntity::getFansId, fansId));
        //是否实名
        activityAwardVO.setIsAuth(ObjectUtils.isNotEmpty(fansAuthEntity)
                && ObjectUtils.isNotEmpty(fansAuthEntity.getCstmNo()) ? 0 : 1);

        String phone = fansActivityDTO.getPhone();
        String openId = null;
        if (StrUtil.isBlank(phone)) {
            //如果手机号为空 说明通过openid参与 根据fansId查询openid
            FansUserEntity userEntity = fansUserService.getOne(FansUserEntity.gw()
                    .eq(FansUserEntity::getFansId, fansId)
                    .eq(FansUserEntity::getAppId, appId)
                    .eq(FansUserEntity::getType, 1));

            log.info("{},FansUserEntity：{}", logPrefix, userEntity);

            if (userEntity == null || StrUtil.isBlank(userEntity.getOpenId())) {
                throw new BizException("用户信息异常");
            }
            openId = userEntity.getOpenId();
        }
        // 检测用户参与限制条件
        JSONObject jsonObject = activitySettingService.checkActivitySetting(fansEntity, appId, redisOutTime, activityEntity);

        //判断此用户fansId是否已经进行迁移过
        OldFansInfoEntity oldFansInfo = handleMigrationStatus(activityAwardVO, fansId, openId, phone);
        if (activityAwardVO.getIsMove() == 1 || oldFansInfo == null) {
            return activityAwardVO;
        }

        log.info("{},老客户信息：{}", logPrefix, oldFansInfo);
        if (oldFansInfo.getScore() == null) {
            oldFansInfo.setScore(0);
        }

        // 获取活动奖品
        List<ActivityAwardAndSettingBo> activityAwardList = awardSettingService.getActivityAwardList(activityId, redisOutTime);
        log.info("活动奖品和配置信息{}", JSONUtil.toJsonStr(activityAwardList));
        if (CollUtil.isEmpty(activityAwardList)) {
            throw new BizException("当前活动无可用奖品");
        }
        for (ActivityAwardAndSettingBo awardAndSettingBo : activityAwardList) {
            sendAwardService.sendScore(fansId, appId, awardAndSettingBo, fansActivityDTO.getActivityChannelId(), true,
                    activityEntity.getAgentNo(), awardAndSettingBo.getAwardId(), Constants.SCORE.ACTIVITY);
        }

//        List<ActivityAwardBO> activityAwardBOList = activityAwardService.getAwardList(activityAwardList);
//        log.info("获取活动奖品返回的信息:{}", JSONUtil.toJsonStr(activityAwardBOList));
//        if (CollUtil.isEmpty(activityAwardBOList)) {
//            throw new BizException("当前活动无可用奖品");
//        }
//
//        for (ActivityAwardBO activityAwardBO : activityAwardBOList) {
//            // 判断奖品是否发完
//            if (Objects.equals(activityAwardBO.getAwardNum(), activityAwardBO.getAwardGet())){
//                log.info("{},奖品已发完：{}", logPrefix, activityAwardBO);
//                throw new BizException("当前活动已结束");
//            }
//            // 增加已领取数量
//            awardScoreService.update(new LambdaUpdateWrapper<AwardScoreEntity>()
//                    .eq(AwardScoreEntity::getScoreId, activityAwardBO.getAwardId()).setSql(" score_get = score_get + 1 "));
//            //唤醒奖励福分
//            ScoreRecordTotalEntity awakeScoreRecordTotal = createScoreRecord(activityAwardBO, fansActivityDTO, "老客户唤醒奖励福分");
//
//            scoreRecordTotalService.addScoreRecordTotal(activityEntity.getAgentNo(), awakeScoreRecordTotal, activityAwardBO.getOverDays(),
//                    activityAwardBO.getOverType(),activityAwardBO.getOverTime());
//            log.info("{}用户:{}增加{}奖励福分", logPrefix, fansId, activityAwardBO.getScoreValue());
//
//        }
        Integer oldScore = oldFansInfo.getScore();
        if (oldScore > 0) {
            List<ActivityAwardBO> activityAwardBOList = activityAwardService.getAwardList(activityAwardList);
            ActivityAwardBO activityAwardBO = activityAwardBOList.get(0);
            activityAwardBO.setScoreValue(oldScore);
            //历史福分的迁移
            ScoreRecordTotalEntity oldScoreRecordTotal = createScoreRecord(activityAwardBO, fansActivityDTO, "历史福分迁移");

            scoreRecordTotalService.addScoreRecordTotal(activityEntity.getAgentNo(), oldScoreRecordTotal, activityAwardBO.getOverDays(),
                    activityAwardBO.getOverType(),activityAwardBO.getOverTime());
            log.info("{}用户:{}增加{}历史福分", logPrefix, fansId, oldFansInfo.getScore());
        }

        //更新Redis中参与的次数
        ActivityUserTimesBO activityUserTimesBO = jsonObject.getObject("activityUserTimesBO", ActivityUserTimesBO.class);
        if (ObjectUtils.isNotEmpty(activityUserTimesBO)){
            activitySettingService.updateRedisParticipateNum(jsonObject.getString("currentTimesKey"), activityUserTimesBO, redisOutTime);
        }
        Boolean userJoinScoreValue = jsonObject.getObject("userJoinScoreValue", Boolean.class);
        if (ObjectUtils.isNotEmpty(userJoinScoreValue)){
            RedisUtil.set(jsonObject.getString("userJoinScoreKey"), userJoinScoreValue, redisOutTime, TimeUnit.MILLISECONDS);
        }

        // 更新迁移状态及fansId
        oldFansInfo.setState(0);
        oldFansInfo.setFansId(fansId);
        oldFansInfo.setSyncTime(DateUtil.date());
        FansSourceEntity source = fansSourceService.findFansSourceByFansId(fansId, appId);
        if(null != source){
//            oldFansInfo.setNewAgentNo(source.getAgentNo());
//            oldFansInfo.setNewAgentName(agentInfoService.getAgentInfo(source.getAgentNo()).getAgentName());
        }
        oldFansInfoService.updateById(oldFansInfo);

        activityAwardVO.setIsMove(1);
        activityAwardVO.setOldClient(true);
        activityAwardVO.setRspTitle("恭喜您，历史福分迁移成功！并奖励80福分");
        return activityAwardVO;
    }

    private OldFansInfoEntity handleMigrationStatus(ActivityAwardVO vo, Long fansId, String openId, String phone) {
        String type = "OPENID";
        OldFansInfoEntity oldFansInfo = oldFansInfoService.getOne(OldFansInfoEntity.gw()
                .eq(OldFansInfoEntity::getFansId, fansId));

        if (oldFansInfo != null && oldFansInfo.getState() == 0) {
            vo.setIsMove(1);
            vo.setRspTitle("您已进行过历史福分的迁移");
            return oldFansInfo;
        }

        if (StrUtil.isNotBlank(openId)) {
            oldFansInfo = oldFansInfoService.getOne(OldFansInfoEntity.gw()
                    .eq(OldFansInfoEntity::getOpenId, openId));
        }

        if (oldFansInfo == null && StrUtil.isNotBlank(phone)) {
            oldFansInfo = oldFansInfoService.getOne(OldFansInfoEntity.gw()
                    .eq(OldFansInfoEntity::getPhone, phone));
            type = "PHONE";
            if (oldFansInfo == null) {
                vo.setRspTitle("当前手机号无历史福分可迁移！");
                return oldFansInfo;
            } else if (oldFansInfo.getState() != null && oldFansInfo.getState() == 0){
                vo.setIsMove(1);
                vo.setRspTitle("当前手机号已用于其他微信号的历史福分迁移!");
                return oldFansInfo;
            }
        }

        if (oldFansInfo == null) {
            vo.setRspTitle("请用其他手机号完成历史福分迁移");
            List<OldFansInfoEntity> oldFansInfoList = oldFansInfoService.list(OldFansInfoEntity.gw()
                    .eq(OldFansInfoEntity::getFansId, fansId)
                    .eq(OldFansInfoEntity::getState, 0));

            if (CollUtil.isNotEmpty(oldFansInfoList)) {
                vo.setIsMove(1);
                vo.setRspTitle("您已完成历史福分迁移！");
            }
            return oldFansInfo;
        }

        if (oldFansInfo.getState() != null && oldFansInfo.getState() == 0) {
            vo.setIsMove(1);
            vo.setRspTitle("您已完成历史福分迁移！");
        }
        return oldFansInfo;
    }

    private ScoreRecordTotalEntity createScoreRecord(ActivityAwardBO awardBO, FansActivityDTO dto, String name) {
        return new ScoreRecordTotalEntity()
                .setScore(awardBO.getScoreValue())
                .setName(name)
                .setFlag(0)
                .setInfoId(awardBO.getAwardId())
                .setInfoType(Constants.SCORE.ACTIVITY)
                .setAppId(dto.getAppId())
                .setFansId(dto.getFansId())
                .setActivityId(dto.getActivityId());
    }

}
